%--------------------------------------------------------------------------
% Script to generate Figure 3 (densities) 
%--------------------------------------------------------------------------

clear; 
clc;
close all

set(0,'defaultTextInterpreter','latex');

dataDir = [pwd, '/', 'Data' ,'/'];
figureDir = [pwd, '/', 'Figures' ,'/'];
[~, ~, ~] = mkdir(figureDir);

nDataSel  = '1';
dataDir   = [dataDir, '/', 'Para', nDataSel ,'/'];
figureDir = [figureDir, '/', 'Para', nDataSel ,'/'];
[~, ~, ~] = mkdir(figureDir);

% load data
agg_data    = csvread( [dataDir, 'aggvar_sim.csv']);
densdraws   = csvread( [dataDir, 'a_cross_sim.csv'] );
employdraws = csvread( [dataDir, 'empl_cross_sim.csv'] );
ss_K        = csvread( [dataDir, 'ss_K.csv'] );
K_exact     = agg_data(:,2) + ss_K;

% set specs and N
K_vec = [4;8;10];
xmin  = 0;
xmax  = 2.6;
xn    = 100;
xgrid = linspace(xmin, xmax, xn);

N = 10000;

nfVARSpec = '3';

% given period tt, draw the estimated density

%periods = [27];
periods = [45 115 155];

for pp = 1:length(periods)
    
    tt = periods(pp);

    densdraws_t     = densdraws(tt,1:N)./K_exact(tt)
    employdraws_t   = employdraws(tt,1:N)
    selecteddraws_t = densdraws_t(employdraws_t==1.0)

    color_choice = ['r','b','k','m'];
    linestyle_choice = ['-',':','-*','--'];

    figure(pp);clf;
    set(figure(pp),'PaperType','usletter','PaperOrientation','Landscape','PaperPosition',[0.1 0.1 11 8.5]);
    histogram(selecteddraws_t, 20, 'Normalization', 'pdf','FaceColor',1/255*[200,200,200],'EdgeColor','none')
    hold on

    for ii = 1:length(K_vec)

        K =  K_vec(ii);
        sNameDir = ['fVAR',nfVARSpec];
        saveDir  = [pwd, '/', 'results/Para', nDataSel ,'/', sNameDir,'/'];
        sNameFile = ['K',num2str(K_vec(ii)),'_fVAR',nfVARSpec];    
        PhatDensValue = csvread( [saveDir, sNameFile, '_PhatDensValue.csv'], 1, 0); % read table starting one row below

        plot(xgrid,PhatDensValue(tt,:),'Color',color_choice(ii),'LineStyle',linestyle_choice(ii),'LineWidth',4)
        hold on

    end
    
    % load and draw true density
    truedDir = [pwd, '/', 'Data/Para', num2str(nDataSel) ,'/'];
    PDensValue = csvread( [truedDir, 'aK_cross_pdf_empl_tt', num2str(45), '.csv']);
    plot(PDensValue(:,1),PDensValue(:,2),'Color','c','LineStyle','-.','LineWidth',4)
%     ylim([0.0 0.5]) 
    if pp == 1
        legend('histogram','K=4','K=8','K=10','truth','Location','northwest')    
    end
    set(gca,'FontSize',30)

    sNameDir = ['fVAR',nfVARSpec];
    figsaveDir = [pwd, '/', 'Figures/Para', nDataSel ,'/', sNameDir,'/'];
    [~, ~, ~] = mkdir(figsaveDir);

    sNameFile = ['Density_tt',num2str(tt),'.pdf'];    

    saveas(figure(pp), [figsaveDir sNameFile] );
    close all

end





